#!/usr/bin/env python

# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""uFramework for exposing handlers as RESTful-like endpoints."""

from google.appengine.dist import use_library
use_library('django', '1.2')
import logging
from lib.loggable import loggable 

__author__ = "Maciej Machulak"
__maintainer__ = "Maciej Machulak"
__email__ = "mmachulak@google.com"

__copyright__ = "Copyright 2011, Google Inc."
__license__ = "Apache License 2.0"
__version__ = "0.1"
__status__ = "Prototype"

def path(path, method = 'GET'):

  def inner_path(handler):

    @loggable('parsing path')    
    def parse_path(self,*args):
      
      logging.debug('request method: %s' % self.request.method)
      logging.debug('valid method: %s' % method)
      
      if self.request.method == method:
        logging.debug('method match, parsing request')
        temp_values = path[1:].split('/')
        arguments = args[0].split('/')
        if len(temp_values) != len(arguments):
          raise RestError('arguments do not match required path')
        counter = 0
        self.rest_params = {}
        for value in temp_values:
          self.rest_params[value.replace('{','').replace('}','')] = arguments[counter]
          counter += 1
      else:
        logging.debug('request method does not match required method.')
      
      handler(self,*args)  
    
    return parse_path
  
  return inner_path

class RestError(Exception):
    """Raised when there is an error with processing a call from the client."""
    def __init__(self, msg):
        Exception.__init__(self)
        self.msg = msg

    def __str__(self):
        return repr(self.msg) 
      
if __name__ == '__main__':
    pass          